package com.gegewa.topic.jdata.sameagain;

import java.text.SimpleDateFormat;
import java.util.*;

public class Utils {

    public static List<String> getMaxWeightKeyList(Map<String, Integer> map) {
        List<String> maxWeightKeyList = new ArrayList<>();
        int maxWeight = 0;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue().intValue() > maxWeight) {
                maxWeightKeyList.clear();
                maxWeightKeyList.add(entry.getKey());
                maxWeight = entry.getValue();
            } else if (entry.getValue().intValue() == maxWeight) {
                maxWeightKeyList.add(entry.getKey());
            }
        }
        return maxWeightKeyList;
    }

    public static Map<Integer, Integer> getWeightWeight(Map<String, Integer> map) {
        Map<Integer, Integer> weightMap = new HashMap<>();
        for (Integer v : map.values()) {
            if (weightMap.containsKey(v)) {
                weightMap.put(v, weightMap.get(v) + 1);
            } else {
                weightMap.put(v, 1);
            }
        }
        return weightMap;
    }

    public static Integer[] getWeightThreeLine(Map<Integer, Integer> weightMap, int count) {
        List<Integer> weightList = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : weightMap.entrySet()) {
            weightList.add(entry.getKey());
        }
        Collections.sort(weightList);
        int currentCount = 0;
        int currentIndex = weightList.size() - 1;
        for (; currentIndex >= 0; currentIndex--) {
            if (currentCount + weightMap.get(weightList.get(currentIndex)) > count) {
                break;
            }
            currentCount += weightMap.get(weightList.get(currentIndex));
        }
        Integer[] minWeight = new Integer[3];
        if (currentIndex + 1 < weightList.size()) {
            minWeight[0] = weightList.get(currentIndex + 1);
        }
        minWeight[1] = weightList.get(currentIndex);
        minWeight[2] = count - currentCount;
        return minWeight;
    }

    public static List<String> getMaxWeightKeyList(Map<String, Integer> map, int count) {
        Map<Integer, Integer> weightMap = getWeightWeight(map);
        Integer[] minWeight = getWeightThreeLine(weightMap, count);
        int weightUp = minWeight[0];
        int weightDown = minWeight[1];
        int weightDownCount = minWeight[2];
        List<String> maxWeightKeyList = new ArrayList<>();
        int currentWeightDownCount = 0;
        for (Map.Entry<String,Integer> entry : map.entrySet()) {
            if (entry.getValue() >= weightUp) {
                maxWeightKeyList.add(entry.getKey());
            } else if (entry.getValue() >= weightDown && ++currentWeightDownCount <= weightDownCount) {
                maxWeightKeyList.add(entry.getKey());
            }
        }
        return maxWeightKeyList;
    }

}
